package com.xzzz.common.nacos.controller;

import cn.hutool.core.collection.CollUtil;
import com.xzzz.common.base.pojo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 服务发现和注册
 *
 * @author xzzz
 */
@RestController
@RequestMapping("/discovery")
public class DiscoveryController {

    @Autowired
    private DiscoveryClient discoveryClient;

    /**
     * 注册实例对象, 单例的, 指当前实例的一些信息
     */
    @Autowired
    private Registration registration;

    @Autowired
    private ServiceRegistry<Registration> registry;

    /**
     * 查询所有服务
     *
     * @return 服务列表
     */
    @GetMapping("/services")
    public R<List<String>> getServices() {
        return R.ok(discoveryClient.getServices());
    }

    /**
     * 查询所有服务的所有实例
     * @return 实例列表
     */
    @GetMapping("/instances")
    public R<List<ServiceInstance>> getInstances() {
        List<String> services = discoveryClient.getServices();
        if (CollUtil.isEmpty(services)) {
            return R.fault("当前无任何服务注册, 无法查询实例");
        }

        List<ServiceInstance> instances = new ArrayList<>();
        for (String service : services) {
            instances.addAll(discoveryClient.getInstances(service));
        }
        return R.ok(instances);
    }

    /**
     * 当前实例
     * @return 当前实例状态, UP / DOWN 两种状态
     */
    @GetMapping("/instance/status")
    public R<?> getInstanceStatus() {
        return R.ok(Optional.ofNullable(registry.getStatus(registration)));
    }

}
